package com.darthsith.droidathome.core.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.darthsith.droidathome.core.dao.SensorDao;
import com.darthsith.droidathome.core.model.Sensor;

@Repository
public class SensorDaoImpl implements SensorDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public void addSensor(Sensor sensor) {
		sessionFactory.getCurrentSession().save(sensor);
	}

	@Override
	public Sensor getSensor(String ipAddress, int pin) {
		return (Sensor) sessionFactory.getCurrentSession()
			.createQuery("FROM SENSOR WHERE IPADDRESS=? AND PIN=?")
				.setParameter(0, ipAddress).setParameter(1, pin).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Sensor> listAll() {
		return sessionFactory.getCurrentSession().createQuery("FROM SENSOR").list();
	}

	@Override
	public void removeSensor(Sensor sensor) {
		String ipAddress=sensor.getIpAddress();
		int pin=sensor.getPin();
		Sensor s=getSensor(ipAddress, pin);
		if (s!=null)
			sessionFactory.getCurrentSession().delete(s);
	}

	@Override
	public void update(Sensor sensor) {
		sessionFactory.getCurrentSession().update(sensor);
	}

}
